package cn.risebd.wechat.wechat.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.alibaba.fastjson.JSON;

import cn.risebd.common.util.UUIDHexGenerator;
import cn.risebd.wechat.core.Wechat;
import cn.risebd.wechat.core.WechatBuilder;
import cn.risebd.wechat.model.js.Config;
import cn.risebd.wechat.wechat.support.WechatSupport;

/**
 * @category 微信JS签名校验
 * 
 * @author yiz
 * @date 2016年5月16日 上午11:18:55
 * @version 1.0.0
 * @copyright pycredit.cn
 */
@Controller
@RequestMapping("wechat_js")
public class WechatJsController {
	private static final Logger logger = LoggerFactory.getLogger(WechatJsController.class);

	@RequestMapping("index")
	public ModelAndView index(String code) {
		ModelAndView mav = new ModelAndView("/index");
		Wechat wechat = WechatBuilder.newBuilder(wechatSupport.getAppId(), wechatSupport.getAppSecret()).build();

		if (null != code && !"".equals(code)) {
			String openId = wechat.base().openId(code);
			logger.info("openId={}", openId);
			mav.addObject("openId", openId);
		} else {
			String url = wechat.base().authUrl("http://edx.risebd.cn/rise-wechatdemo/wechat_js/index", false);
			mav.setView(new RedirectView(url));
		}

		return mav;

	}

	@Autowired
	private WechatSupport wechatSupport;

	@RequestMapping(value = "sign", produces = { "text/json; charset=UTF-8" })
	@ResponseBody
	public String sign(String url) {
		logger.info("请求参数url={}", url);
		String jsApiTicket = wechatSupport.getJSApiTicket();
		Wechat wechat = WechatBuilder.newBuilder(wechatSupport.getAppId(), wechatSupport.getAppSecret()).build();
		String nonStr = UUIDHexGenerator.generate();
		Long timestamp = System.currentTimeMillis() / 1000;
		logger.info("jsApiTicket={},nonStr={},timestamp={},wechat={}", jsApiTicket, nonStr, timestamp,
				JSON.toJSONString(wechat));
		Config config = wechat.js().getConfig(jsApiTicket, nonStr, timestamp, url);
		String result = JSON.toJSONString(config);
		logger.info("加密签名参数result = {}", result);
		return result;
	}
}
